from models.repository import Repository
from service import CollaboratorService
from util.log import Log
from util.redis import Redis
from common.const import BaseConstant

async def createRepository(repository: dict):
    try:
        res = await Repository.create(**repository)
        return res
    except Exception as e:
        raise e

async def getRepositoryListByUserId(userId: int):
    try:
        # 降序排序: 加个 - 号 
        # order_by("-sort_order")
        lst = await Repository.filter(user_id=userId).order_by("sort_order", "-update_time")
        return lst
    except Exception as e:
        raise e

async def getRepositoryById(repositoryId: int):
    try:
        repository = await Repository.filter(id=repositoryId).first()
        return repository
    except Exception as e:
        raise e

async def getRepositoryByShortUri(shortUri: str):
    try:
        repository = await Repository.filter(short_uri=shortUri).first()
        return repository
    except Exception as e:
        raise e

async def deleteRepositoryById(repositoryId: int):
    try:
        cnt = await Repository.filter(id=repositoryId).delete()
        return cnt
    except Exception as e:
        raise e

'''
通过 shortUri 更新 知识库
'''
async def updateRepositoryByShorturi(shortUri: str, requestBody: dict):
    try:
        repository = await getRepositoryByShortUri(shortUri)

        for field in ['title', 'description', 'permission']:
            value = requestBody.get(field)
            if value is not None:
                # 使用 setattr() 函数来设置属性的值
                setattr(repository, field, value)

        result = await repository.save()

        return result
    except Exception as e:
        raise e

'''
获取所有 short Uri
'''
async def allShortUriList():
    try:
        uriList = await Repository.all().values("short_uri")
        return uriList
    except Exception as e:
        raise e

'''
获取用户的写权限
'''
async def getUserWritePermission(repository: Repository, userId):
    try:
        flag = False
        # 私有
        if userId == repository.user_id:
            flag = True

        if repository.permission >= 1:
            # 协作者
            isCollaborator = await CollaboratorService.isCollaborator(repository.id, userId)
            if isCollaborator == True:
                flag = True
                
        return flag
    except Exception as e:
        raise e

'''
获取用户的读权限
'''
async def getUserReadPermission(repository: Repository, userId):
    try:
        flag = False
        if userId == repository.user_id:
            # 作者
            flag = True

        if repository.permission == 2:
            # 公开
            flag = True

        if repository.permission == 1:
            # 协作者
            isCollaborator = await CollaboratorService.isCollaborator(repository.id, userId)
            if isCollaborator == True:
                flag = True
        return flag
    except Exception as e:
        raise e
    
'''
通过 id 列表，获取 知识库列表
'''
async def getRepositoryListByIdList(idList):
    try:
        res = await Repository.filter(id__in=idList).all()
        return res
    except Exception as e:
        raise e
